from django.contrib.auth import logout
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render

# Create your views here.
from blog.models import User
import hashlib


def login_views(request):
    if request.method == 'GET':
        if request.session.get('username') and request.session.get('uuid'):
            return HttpResponse('已登录')
        elif request.COOKIES.get('username') and request.COOKIES.get('uuid'):
            return HttpResponse('已登录')
        else:
            return render(request, template_name='login.html')
    elif request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']

        try:
            user = User.objects.get(username=username)
        except Exception as e:
            return HttpResponse('用户名不存在')
        # if not user:
        #   return HttpResponse('用户名不存在')

        m = hashlib.md5()
        m.update(password.encode())
        password_m = m.hexdigest()

        if password != user.password:
            return HttpResponse('密码错误')

        request.seeion['username'] = username
        request.seesion['uuid'] = user.id

        resp = HttpResponse('登录成功')
        if 'remember' in request.POST:
            resp.set_cookie('username', username, 3600 * 24 * 7)
            resp.set_cookie('uuid', user.id, 3600 * 24 * 7)

        return resp


def reg_views(request):
    if request.method == 'GET':
        return render(request, template_name='register.html')
    elif request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        # 加密
        m = hashlib.md5()
        m.update(password.encode())
        password_m = m.hexdigest()
        old_users = User.objects.filter(username=username)
        if old_users:
            return HttpResponse('用户名已注册')
        # 3.插入数据[明文处理密码]
        try:
            user = User.objects.create(username=username, password=password_m)
        except Exception as e:
            print('---create user error %s' % e)
            return HttpResponse('用户已注册')
        # 免登录三天
        # request.session['username'] = username
        # request.session['uid'] = user.id
        # request.session.set_expiry(259200)
        # return HttpResponse('注册成功')
        request.session['username'] = username
        return HttpResponseRedirect('/blog/index/')


def index(request):
    return render(request, template_name='index.html')


def logout_views(request):
    logout(request)
    return HttpResponseRedirect('/blog/index/')
